package com.sduept.nwld.mobile.rest.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sduept.bigdata.document.core.CommonDocumentProperties;
import com.sduept.bigdata.document.dto.RecordImageDTO;
import com.sduept.bigdata.document.entity.core.CommonDocument;
import com.sduept.bigdata.document.entity.core.CommonDocumentDir;
import com.sduept.bigdata.document.entity.core.RecordImage;
import com.sduept.bigdata.equipment.assessment.dto.EquipmentDTO;
import com.sduept.bigdata.equipment.assessment.enums.SubStationTypeEnum;
import com.sduept.bigdata.equipment.assessment.exception.ParameterException;
import com.sduept.bigdata.equipment.assessment.model.inspection.*;
import com.sduept.bigdata.equipment.assessment.service.*;
import com.sduept.bigdata.equipment.assessment.service.impl.DeductionTaskService;
import com.sduept.cim.ledger.manager.SubstationLedgerManager;
import com.sduept.cim.ledger.model.SubstationLedger;
import com.sduept.nwld.dataserver.equipment.assessment.mobile.dto.*;
import com.sduept.nwld.mobile.manager.MobileUtil;
import com.sduept.nwld.mobile.rest.InspectionTaskService;
import com.sduept.permission.entity.PersonnelEntityBean;
import com.sduept.permission.entity.RoleEntityBean;
import com.sduept.permission.manager.PersonnelManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.inject.Inject;
import java.sql.Timestamp;
import java.util.*;

/**
 * APP待办任务模块rest接口（包含待办，评价等接口）
 * 
 * @author zht
 *
 */
@Slf4j
@RestController
@RequestMapping("/inspectionTaskService")
public class InspectionTaskServiceImpl implements InspectionTaskService {

	@Inject
	private InspectionStationService inspectionStationService;

	@Inject
	private InspectionItemService inspectionItemService;
	
	@Inject
	private InspectionQuestionEquipmentService inspectionQuestionEquipmentService;

	@Inject
	private StandardInspectService standardInspectService;

	@Inject
	private InspectionDocumentService inspectionDocumentService;

	@Inject
	private InspectionPlanService inspectionPlanService;
	
	
	@Inject
	private InspectionQuestionEquipmentFeedbackService feedbackService;


	@Inject
	private MobileUtil mobileUtil;// SQL注入检测类

	@Autowired
	private CommonDocumentProperties pros;

	@Inject
	private SubstationLedgerManager munitMan;

	@Inject
	private AssessmentCimService cimMan;

	@Inject
	private DeductionTaskService deductionService;

	@Inject
	private PersonnelManager personnelManager;

	@GetMapping("/getTaskByUserCode/{userCode}")
	@Override
	public List<InspectionStationDTO> getTaskByUserCode(@PathVariable("userCode")String userCode) {
		return inspectionStationService.getInspectionStationDTOByUserCode(userCode);
//			return inspectionStationService.getUnFinishedPlanByUserCode(userCode);
	}

	@Override
	@GetMapping("/getItemsByInspectionStationId/{inspectionStationId}")
	public List<InspectionItemDTO> getItemsByInspectionStationId(@PathVariable("inspectionStationId") String inspectionStationId) {
		List<InspectionItemDTO> dtos = new ArrayList<>();
		try {
			dtos = inspectionItemService.getItemsByInspectionStationId(inspectionStationId);
		} catch (ParameterException e) {
			log.error("APP厂站id" + inspectionStationId + "获取items失败!!!");
			e.printStackTrace();
		}
		return dtos;
	}

	@GetMapping("/getStandardLibItems")
	@Override
	public List<StandardLibItemDTO> getStandardLibItems() {
		try {
			return standardInspectService.getAvailableStandardLibItems();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new ArrayList<>();
	}

	@Override
	@PostMapping("/updateInspectItems")
	public Rtn updateInspectItems(  @RequestBody String param) {
		JSONArray jsonArray = JSONArray.parseArray(param);
		List<InspectionItemDTO4APP> list = new ArrayList<InspectionItemDTO4APP>();
		for (int i = 0; i < jsonArray.size(); i++) {
			JSONObject json = (JSONObject) jsonArray.get(i);
			list.add(InspectionItemDTO4APP.convertFromJSONObject4APP(json));
		}
		Rtn rtn = new Rtn();
		try {
			inspectionItemService.updateInspectItems(list);
			rtn.setData("success");
		} catch (Exception e) {
			rtn.setRtn(-1);
			rtn.setData("fail");
			log.error("APP 上传分数失败");
			e.printStackTrace();
		}
		return rtn;
	}

	@Override
	@PostMapping("/upLoadInspectItemDTO")
	public Rtn upLoadInspectItemDTO(@RequestBody String param) {
		Rtn rtn = null;
		JSONObject json = JSONObject.parseObject(param);
		InspectionItemDTO4APP inspectionItemDTO4APP = InspectionItemDTO4APP.convertFromJSONObject4APP(json);
		String id = inspectionItemDTO4APP.getInspectionItemId();
		if (null != id && !id.isEmpty()) {
			try {
				InspectionItem item = deductionService.getInspectionItemById(
						inspectionItemDTO4APP.getInspectionStationId(), inspectionItemDTO4APP.getInspectionItemId());
				if (null != item) {
					item.setUpdateTime(new Date(inspectionItemDTO4APP.getInspectTimeMils()));
					item.setActualAssessmentExpertId(inspectionItemDTO4APP.getActualAssessmentExpertId());
					item.setActualAssessmentExpertName(inspectionItemDTO4APP.getActualAssessmentExpertName());
					item.setStatus(1);
					item.setRemaker(inspectionItemDTO4APP.getRemark());
					item.setRecommendation(inspectionItemDTO4APP.getRecommendation());
				}
				deductionService.doDeduction(inspectionItemDTO4APP.getInspectionStationId(),
						inspectionItemDTO4APP.getInspectionItemId(), inspectionItemDTO4APP.getInspectionItemDeduct());
				rtn = new Rtn("success", null, 1);
			} catch (Exception e) {
				rtn = new Rtn(null, inspectionItemDTO4APP.getInspectionItemId() + "计算扣分出错", -1);
				log.error(inspectionItemDTO4APP.getInspectionItemId() + "计算扣分出错！！！");
				e.printStackTrace();
			}
		} else {
			log.error("上传分数失败，itemId为空");
			rtn = new Rtn(null, "itemId为空", -1);
		}
		return rtn;
	}

	@Override
	@PostMapping("/uploadQuestionEquipments")
	public Rtn uploadQuestionEquipments(@RequestBody String params) {
		JSONObject jso = JSONObject.parseObject(params);
		String inspectionStationId = jso.getString("inspectionStationId");
		JSONArray questionEquipments = jso.getJSONArray("questionEquipments");
		Rtn rtn = null;
		List<InspectionQuestionEquipmentDTO> questionEquipmentDtos = new ArrayList<>();
		if (null != questionEquipments) {
			for (int i = 0; i < questionEquipments.size(); i++) {
				questionEquipmentDtos.add(
						InspectionQuestionEquipmentDTO.convertFromJSONObject4APP(questionEquipments.getJSONObject(i)));
			}
		}
		try {
			for (InspectionQuestionEquipmentDTO questionEquipmentDto : questionEquipmentDtos) {
				InspectionQuestionEquipment qe = InspectionQuestionEquipmentDTO
						.convertToInspectionQuestionEquipment(questionEquipmentDto);
				deductionService.createOrUpdateInspectionQuestionEquipment(inspectionStationId,
						questionEquipmentDto.getOid(), qe);
			}
			rtn = new Rtn("success", null, 1);
		} catch (Exception e) {
			rtn = new Rtn("fail", null, -1);
			e.printStackTrace();
		}
		return rtn;
	}

	@Override
	@PostMapping("/deleteQuestionEquipments")
	public Rtn deleteQuestionEquipments(@RequestBody String params) {
		JSONObject jso = JSONObject.parseObject(params);
		String inspectionStationId = jso.getString("inspectionStationId");
		String[] ids = jso.getObject("ids", String[].class);
		try {
			if (ids != null) {
				deductionService.deleteInspectionQuestionEquipment(inspectionStationId, ids);
			}
		} catch (Exception e) {
			log.error(params + "删除问题设备失败");
			return new Rtn("fail", "删除问题设备失败", -1);
		}
		return new Rtn();
	}

	@PostMapping("/updateQuestionEquipmentStatus")
	@Override
	public int updateQuestionEquipmentStatus(@RequestBody Map<String,String> json) {
		String inspectionStationId=json.get("inspectionStationId");
		String inspectionItemId=json.get("inspectionItemId");
		String questionEquipmentId=json.get("questionEquipmentId");
		InspectionQuestionEquipment inspectionQuestionEquipment=inspectionQuestionEquipmentService.findById(questionEquipmentId);
		if(inspectionQuestionEquipment!=null) {
			inspectionQuestionEquipment.setStatus(1);
		}else{
			return 0;
		}
		deductionService.createOrUpdateInspectionQuestionEquipment(inspectionStationId,
				inspectionItemId, inspectionQuestionEquipment);
		return 1;
	}
	
	@Override
	@PostMapping("/uploadImage")
	public Rtn uploadImage(@RequestBody String param) {
		Rtn rtn;
		JSONObject jso = JSONObject.parseObject(param);
		RecordImageDTO4APP recordImageDTO4APP = RecordImageDTO4APP.convertFromJSONObject4APP(jso);
		RecordImageDTO dto = RecordImageDTO4APP.convertToRecordImageDTO(recordImageDTO4APP);
		try {
			String id = inspectionDocumentService.upload(dto);
			rtn = new Rtn(id, null, 1);
		} catch (Exception e) {
			log.error(recordImageDTO4APP.getName() + "保存图片失败");
			rtn = new Rtn(null, "保存图片失败", -1);
			e.printStackTrace();
		}
		return rtn;
	}

	@Override
	@PostMapping("/deleteImage")
	public Rtn deleteImagesByIds(@RequestBody String param) {
		Rtn rtn;
		List<String> list = new ArrayList<>();
		JSONArray jsonArray = JSONArray.parseArray(param);
		if (null != jsonArray) {
			for (int i = 0; i < jsonArray.size(); i++) {
				list.add(jsonArray.getString(i));
			}
		}
		try {
			inspectionDocumentService.deleteImageByid(list);
			rtn = new Rtn("success", null, 1);
		} catch (Exception e) {
			log.error(param + "删除图片失败");
			rtn = new Rtn("fail", "删除图片失败", -1);
			e.printStackTrace();
		}
		return rtn;
	}

	@Override
	@GetMapping("/getHistoryInspectStations/{params}")
	public List<InspectionPlanDTO> getHistoryInspectStations(@PathVariable("params") String params) {
		List<InspectionPlanDTO> result = null;
		JSONObject json = JSONObject.parseObject(params);
		HistoryQueryParamDTO dto = HistoryQueryParamDTO.convertFromJSONObject4APP(json);
		try {
			result = inspectionPlanService.getFinishedByCodeTimeSubName(dto);
		} catch (ParameterException e) {
			e.printStackTrace();
		}
		return result;
	}

	@Override
	@GetMapping("/getDirAndDocs")
	public JSONObject getAllDocument() {
		JSONObject jso = new JSONObject();
		List<CommonDocumentDir> dirs = new ArrayList<>();
		List<CommonDocument> docs = new ArrayList<>();
		try {
			dirs = inspectionDocumentService.findDocumentDir();
			docs = inspectionDocumentService.getAllDocs();
		} catch (Exception e) {
			e.printStackTrace();
		}
		jso.put("dir", dirs);
		jso.put("doc", docs);
		return jso;
	}

	// 根据id获取文件以及文件夹下的文件
	@Override
	@GetMapping("/getAllDirsAndDocsByDirId/{dirId}")
	public EvaluateDirDTO getAllDocumentByDirId(@PathVariable("dirId") String dirId) {
		return inspectionDocumentService.getAllDocumentByDirId(dirId);
	}

//	根据id下载文件
	@Override
	@GetMapping("/downLoadFile/{fileId}")
	public String downLoadFile(@PathVariable("fileId") String fileId) {
		String res = "";
		try {
			fileId = mobileUtil.SQLInjectCheck(fileId);
			res = inspectionDocumentService.downloadDocBase64Str(fileId);
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
		return res;
	}

	@Override
	@GetMapping("/getRecordImagesByOid/{oid}")
	public List<RecordImage> getRecordImagesByOid(@PathVariable("oid") String oid) {
		List<RecordImage> result = new ArrayList<>();
		try {
			result = inspectionDocumentService.findRecordImageIdByOid(oid);
		} catch (Exception e) {
			log.error(oid + "查找图片失败！");
			e.printStackTrace();
		}
		return result;
	}

	@Override
	@GetMapping("/getRecordImageCountByOid/{oid}")
	public int getRecordImageCountByOid(@PathVariable("oid") String oid) {
		List<RecordImage> result = getRecordImagesByOid(oid);
		return result.size();
	}

	@Override
	@GetMapping("/getImageStrById/{id}")
	public Rtn getImageStrById(@PathVariable("id")String id) {
		Rtn rtn = null;
		try {
			String imageStr = inspectionDocumentService.downloadOriginalById(id);
			rtn = new Rtn(imageStr, null, 1);
		} catch (Exception e) {
			rtn = new Rtn(null, "下载图片失败", -1);
			log.error(id + "下载图片失败！");
			e.printStackTrace();
		}
		return rtn;
	}

	@Override
	@GetMapping("/getImageThumbnailStrById/{id}")
	public Rtn getImageThumbnailStrById(@PathVariable("id")String id) {
		Rtn rtn = null;
		try {
			String imageStr = inspectionDocumentService.downloadThumbnailById(id);
			rtn = new Rtn(imageStr, null, 1);
		} catch (Exception e) {
			rtn = new Rtn(null, "下载缩略图失败", -1);
			log.error(id + "下载缩略图失败！");
			e.printStackTrace();
		}
		return rtn;
	}

	@Override
	@GetMapping("/getUnfinishedInspectionPlans/{userCode}")
	public List<InspectionPlanDTO> getUnfinishedInspectionPlans(@PathVariable("userCode")String code) {
		PersonnelEntityBean user = personnelManager.findPersonnelByCode(code);
		List<InspectionPlanDTO> dto = new ArrayList<>();
		// 如果是管理员返回全部
		if (isManager(code)) {
			List<InspectionPlan> plans = inspectionPlanService.findAllUnFinishPlan();
			for (InspectionPlan inspectionPlan : plans) {
				dto.add(InspectionPlanDTO.converFromInspectionPlan(inspectionPlan));
			}
		} else {
			// 如果不是根据登录人名字查找，在InspectionStation 对象中根据迎检人员、管理单位的人员
			List<InspectionPlan> plans = inspectionPlanService.findAllUnFinishPlanWithOutStation();
			for (InspectionPlan inspectionPlan : plans) {
				List<InspectionStation> stations1 = inspectionStationService
						.findByPlanIdAndInspectionScopePersonnel(inspectionPlan, user.getName());
				List<InspectionStation> stations2 = inspectionStationService
						.findByPlanIdAndStationPersonnel(inspectionPlan.getId(), user.getName());
				if (stations1.size() > 0)
					dto.add(InspectionPlanDTO.converFromInspectionPlan(inspectionPlan, stations1));
				if (stations2.size() > 0)
					dto.add(InspectionPlanDTO.converFromInspectionPlan(inspectionPlan, stations2));
			}
		}
		return dto;
	}

	/**
	 * 判断当前用户的身份 如果是管理员，则isAdmin=true 如果是专家，则isExpert=true 管理员的优先级高于专家
	 */
	private boolean isManager(String code) {
		PersonnelEntityBean user = personnelManager.findPersonnelByCode(code);
		// 判断是否为管理员
		Set<RoleEntityBean> roles = user.getRoles();
		for (RoleEntityBean role : roles) {
			if ("管理员".equals(role.getName())) {
				return true;
			}
		}
		return false;
	}

	@Override
	@GetMapping("/getInspectionStationsByPlanId/{planId}/{userCode}")
	public List<InspectionStationDTO> getInspectionStationsByPlanId(@PathVariable("planId")String planId, @PathVariable("userCode")String userCode) {
		List<InspectionStationDTO> result = new ArrayList<>();
		PersonnelEntityBean user = personnelManager.findPersonnelByCode(userCode);
		try {
			// 如果是管理员返回全部
			if (isManager(userCode)) {
				List<InspectionStation> stations = inspectionStationService
						.findByInspectionPlanWithExpertAndItems(planId);
				for (InspectionStation inspectionStation : stations) {
					result.add(InspectionStationDTO.convertFromInspectionStation(inspectionStation));
				}
			} else {
				// 如果不是根据登录人名字查找，在InspectionStation 对象中根据迎检人员、管理单位的人员
				InspectionPlan inspectionPlan = inspectionPlanService.findById(planId);
				List<InspectionStation> stations1 = inspectionStationService
						.findByPlanIdAndInspectionScopePersonnel(inspectionPlan, user.getName());
				List<InspectionStation> stations2 = inspectionStationService
						.findByPlanIdAndStationPersonnel(inspectionPlan.getId(), user.getName());
				if (stations1.size() > 0) {
					for (InspectionStation inspectionStation : stations1) {
						result.add(InspectionStationDTO.convertFromInspectionStation(inspectionStation));
					}
				}
				if (stations2.size() > 0) {
					for (InspectionStation inspectionStation : stations2) {
						result.add(InspectionStationDTO.convertFromInspectionStation(inspectionStation));
					}
				}
			}
		} catch (ParameterException e) {
			log.error("评价计划" + planId + "获取评价厂站失败！！！");
			e.printStackTrace();
		}
		return result;
	}

	@Override

	@GetMapping("/getStationByMaintenanceName/{mname}")
	public List<SubstationLedger> getSubstationByMaintenanceUnit(@PathVariable("mname") String maintenanceUnit) {
		List<SubstationLedger> ledgers = munitMan.queryStationLedgerByCondition(null, null, null, null, maintenanceUnit,
				null, null, null, null, null);
		return ledgers;
	}

	@Override
	@GetMapping("/getEquipmentByStationId/{sid}")
	public List<EquipmentDTO> getEquipmentByStationId(@PathVariable("sid") String sid) {
		return cimMan.findEquipmentDTOsByStation(sid);
	}

	@Override
	@PostMapping("/setInspectionStation")
	public Rtn generateInspectionStation(@RequestBody String params) {
		try {
			JSONObject json = JSONObject.parseObject(params);
			String id = json.getString("id");
			String stationId = json.getString("stationId");
			String stationName = json.getString("stationName");
			String stationType = json.getString("stationType");
			long startTime = json.getLong("startTime");
			long endTime = json.getLong("endTime");
			long actualStartTime = json.getLong("actualStartTime");
			InspectionStation instation = inspectionStationService.findById(id);
			if (null != instation) {
				instation.setStationId(stationId);
				instation.setStationName(stationName);
				instation.setStationType(SubStationTypeEnum.valueOf(stationType));
				if (startTime != 0)
					instation.setStartTime(new Timestamp(startTime));
				if (endTime != 0)
					instation.setEndTime(new Timestamp(endTime));
				if (actualStartTime != 0)
					instation.setActualStartTime(new Timestamp(actualStartTime));
			}

			// 生成计划
			inspectionItemService.generateStationInspectionItems(SubStationTypeEnum.valueOf(stationType),
					instation.getId());
			instation = inspectionStationService.update(instation);

		} catch (Exception e) {
			e.printStackTrace();
			return new Rtn(params, "接受参数数据错误", -1);
		}
		return new Rtn();
	}

	@Override
	@GetMapping("/setInspectionStationStartTime/{inspectionStationId}/{startTimeMils}")
	public Rtn setInspectionStationStartTime(@PathVariable("inspectionStationId") String inspectionStationId,  @PathVariable("startTimeMils")long startTimeMils) {
		Rtn rtn = null;
		InspectionStation inspectionStation=deductionService.getInspectionStationById(inspectionStationId);
		if(inspectionStation==null) {
			inspectionStation = inspectionStationService.findById(inspectionStationId);
		}
		if (null != inspectionStation) {
			inspectionStation.setActualStartTime(new Date(startTimeMils));
			inspectionStation.setStatus(1);
			InspectionStation result = inspectionStationService.update(inspectionStation);
			if (null != result) {
				rtn = new Rtn("success", null, 1);
			} else {
				log.error("设置开始时间失败inspectionStation：" + inspectionStationId);
				rtn = new Rtn("fail", "更新失败", -1);
			}
		} else {
			log.error("没有找到inspectionStation：" + inspectionStationId);
			rtn = new Rtn(null, "没有找到该厂站", -1);
		}
		return rtn;
	}
	@GetMapping("/getAllInspectionPlanNames")
	@Override
	public List<Map<String, String>> getAllInspectionPlanNames() {
		List<Map<String, String>> planName = new ArrayList<Map<String, String>>();
		List<InspectionPlan> plans = inspectionPlanService.findAll();
		for (InspectionPlan inspectionPlan : plans) {
			Map<String, String> map = new HashMap<String, String>();
			map.put("id", inspectionPlan.getId());
			map.put("name", inspectionPlan.getName());
			planName.add(map);
		}
		return planName;
	}

	@Override
	@GetMapping("/getInspectionPlanById/{planId}")
	public InspectionPlanDTO getInspectionPlanById(@PathVariable("planId") String planId) {
		try {
			InspectionPlan inspectionPlan = inspectionPlanService.findById(planId);
			Set<InspectionStation> stations = inspectionStationService.findByInspectionPlan(planId);
			InspectionPlanDTO inspectionPlanDTO = InspectionPlanDTO.converFromInspectionPlan(inspectionPlan, stations);
			return inspectionPlanDTO;
		} catch (ParameterException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	@GetMapping("/getStationDeductDistributionByPlanId/{planId}")
	public JSONObject getStationDeductDistributionByPlanId(@PathVariable("planId") String planId) {
		JSONObject result = new JSONObject();
		Set<InspectionStation> stations = null;
		try {
			stations = inspectionStationService.findByInspectionPlan(planId);
		} catch (ParameterException e) {
			e.printStackTrace();
		}
		if (null != stations) {
			// 统计扣分列表
			List<Map<String, String>> deductList = new ArrayList<>();
			// 饼形图
			Map<String, Integer> pieChartData = new TreeMap<>();
			pieChartData.put("[0-20]", 0);
			pieChartData.put("[20-40]", 0);
			pieChartData.put("[40-60]", 0);
			pieChartData.put("[60-80]", 0);
			pieChartData.put("[80-100]", 0);
			for (InspectionStation inspectionStation : stations) {
				if (StringUtils.isNotEmpty(inspectionStation.getStationName())) {
					Map<String, String> map = new HashMap<String, String>();
					Float deduct = inspectionStation.getDeduct();
					map.put("stationName", inspectionStation.getStationName());
					map.put("deduct", deduct == null ? "0" : deduct + "");
					deductList.add(map);
					if (deduct != null) {
						if (deduct > 0 && deduct <= 20) {
							pieChartData.put("[0-20]", pieChartData.get("[0-20]") + 1);
						} else if (deduct > 20 && deduct <= 40) {
							pieChartData.put("[20-40]", pieChartData.get("[20-40]") + 1);
						} else if (deduct > 40 && deduct <= 60) {
							pieChartData.put("[40-60]", pieChartData.get("[40-60]") + 1);
						} else if (deduct > 60 && deduct <= 80) {
							pieChartData.put("[60-80]", pieChartData.get("[60-80]") + 1);
						} else if (deduct > 80 && deduct <= 100) {
							pieChartData.put("[80-100]", pieChartData.get("[80-100]") + 1);
						}
					}
				}
			}
			Collections.sort(deductList, new Comparator<Map<String, String>>() {
				@Override
				public int compare(Map<String, String> o1, Map<String, String> o2) {
					Float d1 = Float.parseFloat(o1.get("deduct"));
					Float d2 = Float.parseFloat(o2.get("deduct"));
					return d2.compareTo(d1);
				}

			});
			result.put("deductList", deductList);
			result.put("pieChart", pieChartData);
		}
		return result;
	}

	@Override
	@GetMapping("/getQuestionRiskDistributionByPlanId/{planId}")
	public Map<String, Integer> getQuestionRiskDistributionByPlanId(@PathVariable("planId") String planId) {
		Map<String, Integer> levels = new TreeMap<>();
		try {
			List<InspectionItem> inspectionItems = inspectionItemService
					.findCreterionWithQuestionEquipmentsByPlanId(planId);
			for (InspectionItem inspectionItem : inspectionItems) {
				String riskLevel = inspectionItem.getRiskLevel();
				if (StringUtils.isNotBlank(riskLevel)) {
					List<InspectionQuestionEquipment> questionEquipments = inspectionItem.getQuestionEquipments();
					if (questionEquipments != null && questionEquipments.size() > 0) {
						Integer num = levels.get(riskLevel) == null ? 0 : levels.get(riskLevel);
						num++;
						levels.put(riskLevel, num);
					}
				}
			}
		} catch (ParameterException e) {
			log.error(planId + "获取问题设备分布出错！！！");
			e.printStackTrace();
		}
		return levels;
	}
	@GetMapping("/getFeedbackByItemId/{itemId}")
	@Override
	public InspectionQuestionEquipmentFeedback getFeedbackByItemId(@PathVariable("itemId") String itemId) {
		try {
			return feedbackService.findByInspectionItemId(itemId);
		} catch (Exception e) {
			log.error(itemId + "获取意见反馈出错！！！");
			e.printStackTrace();
		}
		return null;
	}

	@Override
	@PostMapping("/saveFeedbackByItemId")
	public Rtn saveFeedbackByItemId(@RequestBody String param) {
		Rtn rtn=new Rtn();
		try {
			JSONObject jso=JSONObject.parseObject(param);
			InspectionQuestionEquipmentFeedback feedback=new InspectionQuestionEquipmentFeedback();
			if(jso.getString("id")!=null) {
				feedback.setId(jso.getString("id"));
			}
			feedback.setFeedback(jso.getString("feedback"));
			feedback.setPlanId(jso.getString("planId"));
			feedback.setInspectionStationId(jso.getString("inspectionStationId"));
			feedback.setInspectionItemId(jso.getString("inspectionItemId"));
			feedback.setFeedbackPersonnel(jso.getString("feedbackPersonnel"));
			feedback.setFeedbackPersonnelPhone(jso.getString("feedbackPersonnelPhone"));
			deductionService.createInspectionQuestionEquipmentFeedback(feedback.getInspectionStationId(), feedback);
		} catch (Exception e) {
			rtn.setRtn(-1);
			e.printStackTrace();
		}
		return rtn;
	}
	@Override
	@PostMapping("/saveFeedbacks")
	public Rtn saveFeedbacks( @RequestBody String param) {
		Rtn rtn=new Rtn();
		try {
			List<InspectionQuestionEquipmentFeedback> feedbacks=new ArrayList<>();
			JSONArray jsonArry=JSONArray.parseArray(param);
			for (int i = 0; i < jsonArry.size(); i++) {
				JSONObject jso=jsonArry.getJSONObject(i);
				InspectionQuestionEquipmentFeedback feedback=new InspectionQuestionEquipmentFeedback();
				if(jso.getString("id")!=null) {
					feedback.setId(jso.getString("id"));
				}
				feedback.setFeedback(jso.getString("feedback"));
				feedback.setPlanId(jso.getString("planId"));
				feedback.setInspectionStationId(jso.getString("inspectionStationId"));
				feedback.setInspectionItemId(jso.getString("inspectionItemId"));
				feedback.setFeedbackPersonnel(jso.getString("feedbackPersonnel"));
				feedback.setFeedbackPersonnelPhone(jso.getString("feedbackPersonnelPhone"));
				feedback.setQustionEquipmentId(jso.getString("qustionEquipmentId"));
				feedbacks.add(feedback);
			}
			if(!feedbacks.isEmpty()) {
				String sId=feedbacks.get(0).getInspectionStationId();
				deductionService.batchCreateOrUpdateInspectionQuestionEquipmentFeedback(sId, feedbacks);
			}
		} catch (Exception e) {
			rtn.setRtn(-1);
			e.printStackTrace();
		}
		return rtn;
	}

	@Override
	@GetMapping("/getFeedbackByInspectionStationId/{inspectionStationId}")
	public List<InspectionQuestionEquipmentFeedback> getFeedbackByInspectionStationId(@PathVariable("inspectionStationId") String inspectionStationId) {
		try {
			return feedbackService.findByInspectionStationId(inspectionStationId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	@PostMapping("/saveEquipment")
	public Rtn saveEquipment(@RequestBody String equipmentDTO) {
		Rtn rtn=new Rtn();
		JSONObject jso=JSONObject.parseObject(equipmentDTO);
		EquipmentDTO dto=new EquipmentDTO(jso.getString("stationName"), jso.getString("stationId"),
				jso.getString("id") ,jso.getString("name") , jso.getString("type"));
		try {
			cimMan.createEquipment(dto);
		} catch (Exception e) {
			rtn.setRtn(-1);
			e.printStackTrace();
		} 
		return rtn;
	}

	@Override
	@GetMapping("/getAllEquipmentTypes")
	public List<String> getAllEquipmentTypes() {
		return cimMan.findAllEquipmentName();
	}

	

}
